package com.jpatest.demo.Service;

import com.github.pagehelper.PageHelper;
import com.jpatest.demo.entity.Company;
import com.jpatest.demo.mapper.CompanyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CompanyServiceImpl {
    @Autowired
    private CompanyMapper companyMapper;

    @CachePut(cacheNames = "company", key = "#company.companyId")
    public Company addCompany(Company company){
        Company companyById = null;
        try {
            int result = companyMapper.insert(company);
            companyById = companyMapper.selectByPrimaryKey(company.getCompanyId());
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return companyById;
    }

    @Cacheable(cacheNames = "companyList", key = "pageNum = " + "#pageNum" + "and" + "pageSize = " + "#pageSize" )
    public List<Company> findAllCompany(int pageNum, int pageSize){
        //将参数传给物理分页
        PageHelper.startPage(pageNum, pageSize);
        return companyMapper.selectAllCompany();
    }

    @Cacheable(cacheNames = "company", key = "#id" )
    public Company getCompanyById(int id){
        Company company = null;
        try {
            company = companyMapper.selectByPrimaryKey(id);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return company;
    }

    @CacheEvict(cacheNames = "company", key = "#id")
    public int deleteCompany(int id){
        return companyMapper.deleteByPrimaryKey(id);
    }

    @CachePut(cacheNames = "company", key = "#company.companyId")
    public Company updateCompany(Company company){
        Company companyById = null;
        try {
            int result = companyMapper.updateByPrimaryKey(company);
            companyById = companyMapper.selectByPrimaryKey(company.getCompanyId());
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return companyById;
    }
}
